<?php
/**
 * Handles all Praise and commenting functions
 *
 * ACCESS: LOGGED IN USERS ONLY FOR POSTING AND COMMENTING, PUBLIC TO READ POST
 *
 * @author Chris Lunsford (Adapted by Alex Poulos)
 * @version 1.0
 */
class Praise extends Controller {
	
	/**
	 * Class constructor
	 */
	function __construct() {
		parent::__construct();
		
		$this->badger->checkRemember();
		
		$this->load->model('UserModel');
		$this->load->model('PraiseModel');
	}
	
	/******************** URL Functions ********************/
	
	/**
	 * Display the last five posts in full
	 */
	function index() {
		$data = $this->_buildContent();
		if (isset($data['loggedin'])) {
			$posts = $this->PraiseModel->getPosts('all','published',5); //public & private, published only, limit 5
		} else {
			$posts = $this->PraiseModel->getPosts('public','published',5); //public & private, published only, limit 5
		}
		foreach($posts->result() as $row) {
			$row->author = $this->UserModel->getUser($row->authorid)->display;
			$row->posted = date('F j, Y - g:ia', $row->posted);
			$row->num_comments = $this->PraiseModel->getComments($row->id, 'approved')->num_rows();
		}
		
		$data['posts'] = $posts;
		$this->load->view('praise/praise', $data);
	}
	
	/**
	 * Display a single post with all comments included
	 */
	function post() {
		$data = $this->_buildContent();
		$user = $this->UserModel->getUserByName($this->session->userdata('username'));
		
		//need to check to make sure a private post isn't being pulled through the url!!
		$post = $this->PraiseModel->getPost($this->uri->segment(3));
		if ($post->public == 0 && !isset($data['loggedin'])) {
			$this->session->set_flashdata('msg_error', 'You must be logged in to view this entry.');
			redirect('praise');
		}
		
		$this->load->library('validation');
		
		$rules['body'] = "trim|required|xss_clean";
		$rules['authorname'] = "trim|xss_clean";
		$rules['postid'] = "required|xss_clean";
		$this->validation->set_rules($rules);
		
		$fields['body']	= 'comment';
		$fields['authorname']	= 'name';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if ($this->validation->run() == TRUE && !$this->input->post('email')) {$this->createComment();}
		
		
		if ($user != NULL && $user->userid == $post->authorid) {
			$data['page_info']['items'][] = '<a href="'.site_url().'praise/editPost/'.$post->id.'">Edit this Entry</a>';
		}
		
		$post->author = $this->UserModel->getUser($post->authorid)->display;
		$post->posted = date('F j, Y - g:ia', $post->posted);
		$data['post'] = $post;

		$comments = $this->PraiseModel->getComments($this->uri->segment(3));
		foreach($comments->result() as $row) {
			$row->author = $row->authorname;
			$row->posted = date('F j, Y - g:ia', $row->posted);
			$row->edit = '';
			$rowe->approve = '';
			if ($row->edited != NULL) { 
				$row->editor = $this->UserModel->getUser($row->edited_by)->display; 
				$row->edited = date('F j, Y - g:ia', $row->edited);
			}
			if ($row->approved === 'n') {
				$row->approve = '<a href="'.site_url().'praise/approveComment/'.$row->id.'">approve comment</a>';
			}
			if (($user != NULL && $user->userid == $row->authorid) || $this->badger->checkMember('admin')) {
				$row->edit = '<a href="'.site_url().'praise/editComment/'.$row->id.'">edit</a>';
			}
		}
		
		$data['comments'] = $comments;
		$this->load->view('praise/post', $data);
	}
	
	/**
	 * Displays page: This is the write page for composing a praise
	 */
	function publish() {
		//Only Admins and XALT can publish for now
	//	$this->badger->checkAllow('admin xalt');
		
		$this->load->library('validation');
		
		$rules['title'] = "trim|required|max_length[255]|prep_for_form|xss_clean";
		$rules['body'] = "trim|required";
		$this->validation->set_rules($rules);
		
		$fields['title']	= 'Title';
		$fields['body']	= 'praise entry';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$data = $this->_buildContent();
			$data['dropdown_publish'] = array('0' => 'Draft', '1' => 'Published');
			$data['dropdown_public'] = array('0' => 'Private', '1' => 'Public');
			$this->load->view('praise/praise_publish',$data);
		} else {
			$post['title'] = $this->input->post('title', TRUE);
			$post['body'] = $this->input->post('body', TRUE);
			$post['authorid'] = $this->UserModel->getUserID($this->session->userdata('username'));
			$post['posted'] = time() + 3600; //add an hour to offset for server time
			$post['public'] = $this->input->post('public');
			$post['published'] = $this->input->post('published');
			
			$this->PraiseModel->createPost($post);
			redirect('praise');
		}
	}
	
	/**
	 * Displays page to allow editing a comment.  The editor must be an admin or the comment's author
	 */
	function editComment() {
		//check to make sure the owner is the one editing this
		//or an admin
		$user = $this->UserModel->getUserByName($this->session->userdata('username'));
		$comment = $this->PraiseModel->getComment($this->uri->segment(3));
		if ($user->userid == $comment->authorid || $this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('admin'))) {
			$this->load->library('validation');
			$rules['authorname'] = "trim|required|xss_clean";
			$rules['body'] = "trim|required|xss_clean";
			$this->validation->set_rules($rules);
		
			$fields['authorname']	= 'name';
			$fields['body']	= 'comment';
			$this->validation->set_fields($fields);
	
			$this->validation->set_error_delimiters('<div class="error">','</div>');
			
			if($this->validation->run() == FALSE) {
				$data = $this->_buildContent();
				$comment->authorname = ($this->validation->authorname != NULL) ? $this->validation->authorname : $comment->authorname;
				$comment->body = ($this->validation->body != NULL) ? $this->validation->body : $comment->body;
				$data['comment'] = $comment;
				$this->load->view('praise/comment_edit',$data);
			} else {
				$post['authorname'] = $this->input->post('authorname', TRUE);
				$post['body'] = $this->input->post('body', TRUE);
				$post['edited'] = time() + 3600; //offset for server time
				$post['edited_by'] = $user->userid;
				$commentid = $this->input->post('commentid');
			
				$this->PraiseModel->updateComment($commentid,$post);
				redirect('praise/post/'.$comment->postid);
			}
		} else {
			redirect('site/deadend'); //redirect them somewhere more useful and flash an error here!
		}
	}
	
	/**
	 * Displays page: Edit a Post
	 */
	function editPost() {
		//check to make sure the owner is the one editing this
		//or an admin
		$user = $this->UserModel->getUserByName($this->session->userdata('username'));
		$post = $this->PraiseModel->getPost($this->uri->segment(3));
		if ($user->userid == $post->authorid || $this->badger->checkAllow('admin')) {
			$data = $this->_buildContent();
			$data['post'] = $post;
			$data['dropdown_publish'] = array('0' => 'Draft', '1' => 'Published');
			$data['dropdown_public'] = array('0' => 'Private', '1' => 'Public');
			$this->load->view('praise/praise_edit', $data);
		} else {
			redirect('side/deadend'); //somewhere more useful with a flash error, please
		}
	}
	
	/******************* Task Functions *******************/
	
	/**
	 * Creates a comment for a given praise entry.  The author is the current logged in user
	 * The author supplies their own choice of name, until the user profiles are updated.
	 *
	 */
	function createComment() {
		//$this->badger->checkState();
		
		$post['body'] = $this->input->post('body', TRUE);
		$post['authorid'] = $this->UserModel->getUserID($this->session->userdata('username'));
		$post['authorname'] = (!$this->input->post('authorname')) ? "anonymous" : $this->input->post('authorname',TRUE) ;
		$post['postid'] = $this->input->post('postid');
		$post['posted'] = time() + 3600; //time offset for server time
		if($this->session->userdata('loggedin')) $post['approved'] = 'y';
		$this->PraiseModel->createComment($post);
		
		if(!$this->session->userdata('loggedin')) $this->session->set_flashdata('msg_info', 'thanks for submitting a comment. it will appear once it has been approved.');
		
		redirect('praise/post/'.$this->input->post('postid'));
	}
	
	/**
	 * Approves a comment for viewing.
	 *
	 */
	function approveComment() {
		$this->badger->checkAllow('admin xalt');
		
		$comment = $this->PraiseModel->getComment($this->uri->segment(3));
		$post['approved'] = 'y';
		$this->PraiseModel->updateComment($comment->id,$post);
				
		redirect('praise/post/'.$comment->postid);
	}
	
	/**
	 * Edits a post with submitted information
	 */
	function doEditPost() {
		$this->badger->checkAllow('admin xalt');
		$post['title'] = $this->input->post('title', TRUE);
		$post['body'] = $this->input->post('body', TRUE);
		$post['edited_by'] = $this->UserModel->getUserID($this->session->userdata('username'));
		$post['edited'] = time() + 3600; //time offset for server
		$post['public'] = $this->input->post('public');
		$post['published'] = $this->input->post('published');
		$id = $this->input->post('id');
			
		$this->PraiseModel->updatePost($id,$post);
		redirect('praise');
	}
	
	/**
	 * Deletes a post from the database
	 */
	function deletePost() {
		$this->badger->checkAllow('admin');
		$this->PraiseModel->deletePost($this->uri->segment(3));
		redirect('praise');
	}
	
	/**
	 * Deletes a comment
	 */
	function deleteComment() {
		$this->badger->checkAllow('admin');
		$this->PraiseModel->deleteComment($this->uri->segment(3));
		redirect('praise');
	}
	
	/*
	 * Supplies user-specific information to the interface for customization
	 */
	function _buildContent() {
		//REQUIRED//
		$data['page_info']['title'] = 'praise';
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');
		if ($this->session->flashdata('msg_error')) $data['msg_error'] = $this->session->flashdata('msg_error');
		
		//test if user is logged in for site navigation
		if ($this->session->userdata('loggedin')) {
			//grab the user
			$user = $this->UserModel->getUserByName($this->session->userdata('username'));
			
			$data['loggedin'] = TRUE;
			$data['con_user'] = $user;
			$data['sidebar'] = TRUE;
			
			//is admin?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('admin'))) {
				$data['admin_tab'] = TRUE;
			}
		
			//is xalt?
//			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('xalt'))) {
				$data['page_info']['items'][] = anchor('praise/publish', 'Compose entry');
//			}
			
			//is prayer team?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('lg_pop'))) {
				$data['prayer_tab'] = TRUE;
			}
		}
		
		return $data;
	}
}
?>
